<template>
  <div class="marketing-activity-list">
    <el-collapse-transition>
      <div v-show="!isShowEffect">
        <div class="top">
          <div class="app-main-top-box"><div class="title">活动列表</div></div>
          <div class="tab">
            <el-tabs v-model="filterForm.timeState" @tab-click="changeTab">
              <el-tab-pane label="进行中" name="1" />
              <el-tab-pane label="未开始" name="2" />
              <el-tab-pane label="已失效" name="3" />
            </el-tabs>
          </div>
        </div>

        <!-- 列表 -->
        <div class="bottom app-main-content-box">
          <div class="flexRBC">
            <div class="list-search">
              <el-input v-model="filterForm.theme" placeholder="请输入活动名称" size="small" class="input-with-select" @keyup.enter.native="searchByKeyword" />
              <el-button :loading="searchLoading" type="primary" size="small" round icon="el-icon-search" @click="searchByKeyword">查 询</el-button>
            </div>
          </div>

          <div class="content">
            <!-- 表格内容 -->
            <div class="list-table">
              <el-table v-loading="tableLoading" :data="list" border stripe style="width: 100%" size="small" element-loading-text="加载中" empty-text="暂无数据">
                <el-table-column prop="theme" label="活动主题" fixed />
                <el-table-column label="活动时间" width="150">
                  <template slot-scope="scope">
                    <div>开始时间：{{ scope.row.startTime }}</div>
                    <div>结束时间：{{ scope.row.endTime }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="活动状态">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.status === 1" size="mini" type="success">启用中</el-tag>
                    <el-tag v-if="scope.row.status === 2" size="mini" type="danger">已暂停</el-tag>
                    <el-tag v-if="scope.row.status === 3" size="mini" type="info">已终止</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="活动类型">
                  <template slot-scope="scope">
                    <div>
                      {{ scope.row.onlyMemberDay ? '会员日' : '' }}{{ $store.state.setting.marketingActivityTypeKeyOptions[scope.row.activityType] || '-' }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="参与对象">
                  <template slot-scope="scope">
                    <div v-if="scope.row.participant === 1">所有人</div>
                    <div v-else-if="scope.row.participant === 2">所有会员</div>
                    <div v-else-if="scope.row.participant === 3 || scope.row.participant === 6">{{ scope.row.memberCategory }}</div>
                    <div v-else-if="scope.row.participant === 4">指定手机用户</div>
                    <div v-else-if="scope.row.participant === 5">指定银行卡用户</div>
                  </template>
                </el-table-column>
                <el-table-column label="总预算">
                  <template slot-scope="scope">
                    <div v-if="scope.row.budget === -1">不限</div>
                    <div v-else>{{ scope.row.budget }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="issued" label="已投放" />
                <el-table-column label="剩余预算" width="150">
                  <template slot-scope="scope">
                    <div v-if="scope.row.budget === -1">不限</div>
                    <div v-else class="flexRBC">
                      <span>{{ scope.row.remainBudget | parseNumberToThousands(0, false) }}</span>
                      <div v-if="scope.row.status === 1 || scope.row.status === 2">
                        <el-button type="text" size="small" style="display:inline-block" @click="addBudget(scope.row)">增加</el-button>
                        <el-button type="text" size="small" style="display:inline-block" class="app-text-color-danger" @click="reduceBudget(scope.row)">
                          减少
                        </el-button>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="350">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" @click="openActivityDetail(scope.row)">活动详情</el-button>
                    <el-button v-if="scope.row.status === 1 || scope.row.status === 2" type="text" size="small" @click="goEditActivity(scope.row)">
                      修改活动
                    </el-button>
                    <el-button v-if="scope.row.status === 1 || scope.row.status === 2" type="text" size="small" @click="openModifyStatus(scope.row)">
                      状态管理
                    </el-button>
                    <!-- <el-button
                      v-if="scope.row.status===1"
                      type="text"
                      size="small"
                      @click="openShareQrcode(scope.row)"
                    >二维码和分享</el-button>-->
                    <el-button
                      v-if="!$store.getters.banBtnList.includes('BTN_MCH_CHECK_MARKTING_DATA')"
                      type="text"
                      size="small"
                      @click="openActivityEffect(scope.row)"
                    >
                      活动效果
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig" @sizeschange="sizesChange" @pagechange="pageChange" />
            </div>
          </div>
        </div>
      </div>
    </el-collapse-transition>

    <!-- 效果详情 -->
    <el-collapse-transition><activity-effect v-if="isShowEffect" ref="activityEffect" /></el-collapse-transition>

    <!-- 弹框 -->
    <DialogActivityStatus ref="activityStatus" />
    <DialogActivityQrcode ref="activityQrcode" />
    <DialogActivityDetail ref="activityDetail" />
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import DialogActivityStatus from './components/DialogActivityStatus'
import DialogActivityQrcode from './components/DialogActivityQrcode'
import DialogActivityDetail from './components/DialogActivityDetail'
import ActivityEffect from './components/ActivityEffect'
import { validateCustomPositiveInt } from '@/utils/validate'
import { getVipList } from '@/api/vip'
import { getActivityList, modifyActivityBudget } from '@/api/marketing'
export default {
  components: {
    DialogActivityStatus,
    DialogActivityQrcode,
    DialogActivityDetail,
    ActivityEffect
  },
  data() {
    return {
      // 配置
      // 分页
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      // 状态
      tableLoading: false, // 表格loading
      searchLoading: false,
      isShowEffect: false,
      // 数据
      list: [], // 表格数据
      filterForm: {
        theme: '',
        timeState: '1' // tab 激活
      },
      filterType: 'all'
    }
  },
  mounted() {
    if (this.$route.params.timeState) {
      this.filterForm.timeState = this.$route.params.timeState
    }
    this.fetchData(1)
    this.getActiveMaIsOnline()
  },
  methods: {
    /**
		 *  获取数据
		 */
    // 获取小程序是否上线
    ...mapActions(['getAuthMa']),
    getActiveMaIsOnline() {
      this.getAuthMa()
    },

    // 获取列表
    fetchData(page = this.paginationConfig.page, pageSize = this.paginationConfig.pageSize) {
      // 加入page
      this.filterForm.page = page
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.tableLoading = true
      getActivityList(params)
        .then(res => {
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .finally(() => {
          this.tableLoading = false
          this.searchLoading = false
        })
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    /**
		 * 按钮组
		 */
    // 更改tab
    changeTab(tab, event) {
      this.filterForm.theme = ''
      this.fetchData(1)
    },

    // 点击搜索
    searchByKeyword() {
      this.searchLoading = true
      this.fetchData(1)
    },

    // 增加库存
    addBudget(row) {
      // 判断是否已达上限
      if (row.remainBudget >= 99999999) {
        this.$alert('剩余预算已达到上限', '温馨提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {}
        })
      } else {
        const nowBudget = row.remainBudget
        const addMax = 99999999 - row.remainBudget
        this.$prompt(`当前剩余预算：${nowBudget}（最多可增加${addMax}）`, '请输入新增预算数量', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          inputValidator: function validateAdd(val) {
            if (val === '' || val == null) {
              return '请输入新增预算数量'
            } else if (!validateCustomPositiveInt(val, 0)) {
              return '请输入正整数'
            } else if (val > addMax) {
              return `已超过最大可增加数量（最多可增加${addMax}）`
            }
          }
        })
          .then(({ value }) => {
            const params = {
              activityId: row.id,
              amount: value
            }
            this.tableLoading = true
            modifyActivityBudget(params)
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: '增加预算成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.fetchData()
              })
              .catch(err => {
                this.tableLoading = false
              })
              .finally(() => {})
          })
          .catch(() => {})
      }
    },

    // 减少预算
    reduceBudget(row) {
      // 判断剩余库存
      if (row.remainBudget <= 0) {
        this.$alert('剩余预算已不足', '温馨提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {}
        })
      } else {
        const nowBudget = row.remainBudget
        this.$prompt(`当前剩余预算：${nowBudget}（最多可减少${nowBudget - 1}）`, '请输入减少预算数量', {
          confirmButtonText: '保存',
          cancelButtonText: '取消',
          inputValidator: function validateAdd(val) {
            if (val === '' || val == null) {
              return '请输入减少预算数量'
            } else if (!validateCustomPositiveInt(val, 0)) {
              return '请输入正整数'
            } else if (val >= nowBudget) {
              return `已超过最大可减少数量（最多可减少${nowBudget - 1}）`
            }
          }
        })
          .then(({ value }) => {
            const params = {
              activityId: row.id,
              amount: -value
            }
            this.tableLoading = true
            modifyActivityBudget(params)
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: '减少预算成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.fetchData()
              })
              .catch(err => {
                this.tableLoading = false
              })
              .finally(() => {})
          })
          .catch(() => {})
      }
    },

    // 修改活动
    goEditActivity(row) {
      if (row.status === 1) {
        this.$confirm('该活动启用中，请先暂停活动后再修改活动。', '温馨提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning',
          center: true,
          roundButton: true
        })
          .then(() => {})
          .catch(() => {})
      } else {
        this.$router.push({
          name: 'MarketingActivityForm',
          query: { id: row.id, timeState: this.filterForm.timeState }
        })
      }
    },

    // 状态管理
    openModifyStatus(row) {
      this.$refs.activityStatus.open(row).then(res => {
        this.fetchData()
      })
    },

    // 二维码分享
    openShareQrcode(row) {
      if (!this.$store.state.wechat.maInfo.DEFAULT.isOnline) {
        this.$alert('商户小程序未正式发布，暂时不可以获取二维码！', '提示', {
          confirmButtonText: '确定',
          center: true,
          type: 'warning',
          callback: action => {}
        })
      } else {
        this.$refs.activityQrcode.open(row).then(res => {})
      }
    },

    // 打开详情

    openActivityDetail(row) {
      this.$refs.activityDetail.open(row).then(res => {})
    },

    // 活动效果
    openActivityEffect(row) {
      this.isShowEffect = true
      this.$nextTick(() => {
        this.$refs.activityEffect.fetchData(row).then(res => {
          this.isShowEffect = false
        })
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* tab */
::v-deep {
	.el-tabs__header {
		margin-bottom: 0;
		background-color: #fff;
		border-radius: 0 0 5px 5px;
	}
	.el-tabs__nav-wrap::after {
		background-color: #fff;
	}
	.el-tabs__active-bar {
		height: 4px;
	}
}

/* 头部 */
.top {
	padding: 24px 30px 0;
	border-radius: 5px 5px;
	background-color: #fff;
	margin-bottom: 10px;
	.title {
		font-size: 20px;
	}
}

/*搜索  */
.list-search {
	.el-input {
		width: 40%;
		min-width: 400px;
		max-width: 700px;
		margin-right: 10px;
	}
}

/* 表格内容 */
.content {
	margin-top: 10px;
}
</style>
